package com.example.bumenguanli.Filter;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@Component
public class SessionFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpSession session = httpRequest.getSession(false);

        String requestURI = httpRequest.getRequestURI();

        // 检查是否为公开资源或页面
        if (isPublicResource(requestURI)) {
            chain.doFilter(request, response);
            return;
        }

        // 检查是否已登录
        if (session == null || session.getAttribute("user") == null) {
            // 未登录，重定向到登录页
            httpResponse.sendRedirect("/login.html");
            return;
        }

        // 已登录，继续处理请求
        chain.doFilter(request, response);
    }

    private boolean isPublicResource(String path) {
        return path.equals("/login.html") ||
                path.equals("/register.html") ||
                path.startsWith("/css/") ||
                path.startsWith("/js/") ||
                path.startsWith("/images/") ||
              
                path.equals("/api/login") || // 确保登录API是公开的
                path.equals("/api/register")||
                path.equals("/workers") ||     // 添加 workers 路径
                path.startsWith("/workers/");
    }
}